<template>
  <div class="app">
    <div class="form">
      <el-form :model="userForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="账号" prop="username">
          <el-input type="text" v-model="userForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="userForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import qs from "qs";

export default {
  name:'login',
  data() {

    return {
      userForm: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { min: 2, max: 12, message: '长度在 2 到 12个字符', trigger: 'blur' }
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {

      this.$refs[formName].validate((valid) => {
        console.log("1")
        if (valid) {
          console.log("2")
          let vm=this;
         // let data=qs.stringify({"username":vm.userForm.username,"password":vm.userForm.password});
          // vm.$router.push('/home');
          axios({
            method: "post",
            url: 'user/login',
            data: {username:vm.userForm.username,password:vm.userForm.password},
            headers: {
              "Content-Type": 'application/json'
            }
          }).then(res=>{
            if (res.data.success===true){
              vm.$message.success('登陆成功');
              sessionStorage.setItem("token",res.data.data.token);
              vm.$router.push('/home');
            }else {
              //错误提示
              vm.$message.error('用户名或密码错误');
              vm.$router.push('/login');
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style>
  .app{
    width: 100%;
  }
  .form{
    margin:0 auto;
    width: 30%;
    height: 30%;
  }
</style>
